<template>
  <div class="page-view">
    <div class="page-top df jc-sb">
      <div style="" class="df-c">
        <!-- v-if="system&& system.roles.includes('superadmin')" -->
        <lay-button size="sm" v-if="system&& system.roles.includes('superadmin') && isEditFull == '1'" type="primary" @click="edit_msg">{{ editBtn?'完成':'修改填写信息' }}</lay-button>
      </div>
      <div>
        <h1>对比排序</h1>
      </div>
      <!-- <el-button @click="backPre" class="btn">关闭</el-button> -->
      <lay-button @click="backPre" class="btn layui-btn " size="sm"> 关闭</lay-button>
    </div>
    <div v-if="userList.length > 0" style="padding:0 20px;box-sizing:border-box;">
      <div class="detail_tabs">
        <el-scrollbar style="width:  '100%' ;white-space: nowrap;background:'#fff' ">
          <ul class="df" style="height:45px;background-color: #fff;">
            <li v-for="(item, index) in userList" :key="index" style="padding:0 6px;cursor: pointer;" class="df jcc ai-c" @click="tabClick(item.userName,item.key,item.status)">
              <span
                :style="{color:item.status=='1'?'#1e9fff':'red',padding:'8px 16px','border-bottom':`${currentUser==item.key?'2px solid ':''}`,'border-color':`${item.status=='1'?'#1e9fff':'red'}`}">{{item.userName}}</span>
            </li>
          </ul>
        </el-scrollbar>
      </div>

      <!-- <el-tabs v-model="currentUser" @tab-click="tabClick">
        <el-tab-pane v-for="(user) in userList" :key="user.key" :label="user.userName" :name="user.key">
          <template #label>
            <div :style="{color:user.status=='1'?'':'red'}">
              {{user.userName}}
            </div>
          </template>
        </el-tab-pane>
      </el-tabs> -->

      <el-table :data="tableData" style="width: 100%;margin-top: 20px" height="60vh" stripe :span-method="mergeMethod" empty-text="暂无评价">
        <el-table-column prop="firstName" label="品牌" width="150" align="center">
          <template #default="{row, $index}">
            <div class="smoke_box" @click="setSortFn(row, $index)">
              <span>{{ row.firstName }} </span>
              <span class="smoke_tip" v-if="editBtn">{{ getSortFn(row, $index) }} </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="endName" label="编号" width="150" align="center">
          <template #default="{row, $index}">
            <span class="smoke_tip" v-if="editBtn">
              <el-input @blur="inp_blueNum(row)" v-if="editBtn" v-model="row.endName" size="small" style="width: 70px;"></el-input>
            </span>
            <span v-else>
              {{ row.endName }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="香气特性" align="center">
          <el-table-column prop="aromaQuality" label="香气质" align="center">
            <template #default="{row}">

              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'aromaQuality',['1','3'])">{{ row.aromaQuality||'-' }}</lay-button>
              <!-- <el-input @blur="inp_blue(row,$event)" v-if="editBtn" v-model="row.aromaQuality" size="small" style="width: 70px;"></el-input>
              <div v-else>{{ row.aromaQuality }}</div> -->
              <span v-else>{{ row.aromaQuality||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="aromaVolume" label="香气量" align="center">
            <template #default="{row}">
              <!-- <span>{{ row.aromaVolume||'-' }}</span> -->
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'aromaVolume',['1','3'])">{{ row.aromaVolume||'-' }}</lay-button>
              <span v-else>{{ row.aromaVolume||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="transdermal" label="透发性" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'transdermal',['1','3'])">{{ row.transdermal||'-' }}</lay-button>
              <span v-else>{{ row.transdermal||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="impure" label="杂气" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'impure',['1','3'])">{{ row.impure||'-' }}</lay-button>
              <span v-else>{{ row.impure||'-' }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="烟气特性" align="center">
          <el-table-column prop="density" label="浓度" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'density',['2','3'])">{{ row.density||'-' }}</lay-button>
              <span v-else>{{ row.density||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="energy" label="劲头" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'energy',['2','3'])">{{ row.energy||'-' }}</lay-button>
              <span v-else>{{ row.energy||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="delicacyLevel" label="细腻程度" align="center" min-width="90">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'delicacyLevel',['1','3'])">{{ row.delicacyLevel||'-' }}</lay-button>
              <span v-else>{{ row.delicacyLevel||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="clustering" label="成团性" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'clustering',['1','3'])">{{ row.clustering||'-' }}</lay-button>
              <span v-else>{{ row.clustering||'-' }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="口感特性" align="center">
          <el-table-column prop="thrill" label="刺激性" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'thrill',['1','3'])">{{ row.thrill||'-' }}</lay-button>
              <span v-else>{{ row.thrill||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="dryFeeling" label="干燥感" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'dryFeeling',['1','3'])">{{ row.dryFeeling||'-' }}</lay-button>
              <span v-else>{{ row.dryFeeling||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sweetness" label="甜度" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'sweetness',['1','3'])">{{ row.sweetness||'-' }}</lay-button>
              <span v-else>{{ row.sweetness||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="aftertaste" label="余味" align="center">
            <template #default="{row}">
              <lay-button v-if="editBtn" size="xs" style="padding: 0 10px;text-align: center;" @click="edit_pad(row,'aftertaste',['1','3'])">{{ row.aftertaste||'-' }}</lay-button>
              <span v-else>{{ row.aftertaste||'-' }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column prop="qualitySorting" label="对比排序" width="150" align="center">
          <template #default="{$index}">
            <div v-if="tableData.length > $index && editBtn">
              <!-- <span>{{ tableData[$index+1].qualitySorting }}</span> -->
              <span>{{tableData[$index+1].qualitySorting.split(!tableData[$index+1].sortSymbol?'>':tableData[$index+1].sortSymbol)[0]}}</span>

              <span @click="selectSymbol(tableData[$index+1])"
                style="background-color: #f5f5f5;padding: 2px;color: #999;cursor: pointer;">{{!tableData[$index+1].sortSymbol?'点击选择':tableData[$index+1].sortSymbol}}</span>

              <span>{{tableData[$index+1].qualitySorting.split(!tableData[$index+1].sortSymbol?'>':tableData[$index+1].sortSymbol)[1]}}</span>
            </div>
            <div v-else>{{  tableData[$index+1].qualitySorting}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="styleDescription" label="整体描述" width="150" align="center">
          <template #default="{$index}">
            <div v-if="tableData.length > $index">
              <span v-if="!editBtn">{{ tableData[$index+1].styleDescription }}</span>
              <el-input v-model="tableData[$index+1].styleDescription" v-else @blur="editDescrip($index)" type="textarea" :row="3" placeholder="请输入该品牌的整体描述" />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- <div class="line">
        <div class="line-left">质量排序</div>
        <div class="line-content">
          <span class="show_content" v-if='form.qualitySorting'>
            <span >{{ form.qualitySorting }}</span>
          </span>
          <span class="def_content" v-else>暂无</span>

        </div>
      </div>
      <div class="line">
        <div class="line-left">整体质量描述</div>
        <div class="line-content">
          <span class="show_content" v-if='form.styleDescription'>
            <span v-if="editBtn"><el-input type="text" v-model="form.styleDescription" id=""  @blur="blur" /></span>
            <span v-else>{{ form.styleDescription }}</span> 
          </span>
          <span class="def_content" v-else>暂无描述</span>
        </div>
      </div> -->

    </div>

    <div v-else>
      <el-empty description="暂无人员数据" />
    </div>

    <lay-layer v-model="pad_visible" title="请选择" :area="['250px', '150px']">
      <div style="padding: 20px;">
        <lay-button v-if="showContent.includes('1')" :type="thisRes == '√'?'primary':''" @click="edit_pad_enter('√')">√</lay-button>
        <lay-button v-if="showContent.includes('2')" :type="thisRes == '+'?'primary':''" @click="edit_pad_enter('+')">+</lay-button>
        <lay-button v-if="showContent.includes('3')" :type="thisRes == '0'?'primary':''" @click="edit_pad_enter('0')">0</lay-button>
      </div>
    </lay-layer>

    <lay-layer v-model="symbl_visible" title="请选择" :area="['250px', '150px']">
      <div style="padding: 20px;">
        <lay-button @click="updateSymbol('>')"> > </lay-button>
        <lay-button @click="updateSymbol('<')"> {{ '<' }} </lay-button>
        <lay-button @click="updateSymbol('=')"> = </lay-button>
      </div>
    </lay-layer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import http from "@/http";
import { useRouter, useRoute } from "vue-router";
import { useCounterStore } from "@/current";
import { storeToRefs } from "pinia"; // cnpm i pinia --save  2.1.3
import { layer } from "@layui/layer-vue";
import { ElMessage } from "element-plus";

const store = useCounterStore();
const { system } = storeToRefs(store); //  数据

const router = useRouter();
const currentRout = useRoute();
const id = ref(currentRout.query.id);
const meetingStatus = ref(currentRout.query.status);
// 用户列表
let userList = ref<Array<any>>([]);
// 当前用户
let currentUser = ref<string>("1");
// 用户的数据列表
let tableData = ref<Array<any>>([]);
// 排序的列表
let sortList = ref<Array<string>>([]);
// 用来存储数据和用户的关系
let dataMap = new Map();

let form = ref<any>({});

// onMounted(() => {
//   getDataFn();
//   setInterval(() => {
//     getDataFn();
//   }, 3000);
// });

// 实时刷新页面数据
const isStartInter = ref(false);
const timer = ref<any>(null);
onMounted(() => {
  getDataFn();

  startTimer();
});
const startTimer = () => {
  if (meetingStatus.value == "2") {
    return false;
  }
  timer.value = setInterval(() => {
    isStartInter.value = true;
    getDataFn();
  }, 3000);
};

onBeforeUnmount(() => {
  clearInterval(timer.value);
});

// 获取排序
function getSortFn(row: any, index: number) {
  // let temp:string = ""
  // sortList.value.forEach((ele,index)=>{
  //   if(ele==value) {
  //     temp = String(index + 1)
  //   }
  // })
  // return temp
  // && row.qualitySorting&&row.qualitySorting.split('优于')[0]

  console.log(row, index);

  let from = row;

  if ((index + 1) % 2 !== 0) {
    //奇数行
    console.log(index);
    from = tableData.value[index + 1];
  }

  let sort = from.qualitySorting || "";
  let smokeName = row.smokeName || "";

  if (smokeName === "" || sort == "") {
    return "";
  }

  let good = from.qualitySorting.split(" 优于 ")[0];
  console.log(smokeName);
  console.log(good);

  if (smokeName == good) {
    return "优";
  } else {
    return "";
  }

  // if (sort.indexOf(smokeName) === 0) {
  //   return "优";
  // } else {
  //   return "";
  // }
}

// 设置排序
function setSortFn(row: any, index: number) {
  if (!editBtn.value) {
    return;
  }

  let editFrom = row; //需要修改的数值
  let sort = "";
  if ((index + 1) % 2 === 0) {
    sort = `${row.smokeName} > ${tableData.value[index - 1].smokeName}`;
  } else {
    editFrom = tableData.value[index + 1];
    sort = `${row.smokeName} > ${editFrom.smokeName}`;
  }
  editFrom.qualitySorting = sort;

  editSort(editFrom);

  // if (!editBtn.value) {
  //   return;
  // }

  // let editFrom = row; //需要修改的数值
  // let sort = "";
  // if ((index + 1) % 2 === 0) {
  //   sort = `${row.smokeName} 优于 ${tableData.value[index - 1].smokeName}`;
  // } else {
  //   editFrom = tableData.value[index + 1];
  //   sort = `${row.smokeName} 优于 ${editFrom.smokeName}`;
  // }
  // editFrom.qualitySorting = sort;

  // editSort(editFrom);
}

const smbolRow = ref();
const symbl_visible = ref(false);
const selectSymbol = (row) => {
  console.log(row);
  smbolRow.value = row;
  symbl_visible.value = true;
};
const updateSymbol = async (val) => {
  let sortArr = smbolRow.value.qualitySorting.split(!smbolRow.value.sortSymbol ? "优于" : smbolRow.value.sortSymbol);
  console.log(sortArr);
  smbolRow.value.qualitySorting = sortArr.join(val);
  smbolRow.value.sortSymbol = val;
  console.log(smbolRow.value);
  await editSort(smbolRow.value);
  symbl_visible.value = false;
};
/**合并单元格 */
function mergeMethod({ rowIndex, columnIndex }: any) {
  if (columnIndex === 14 || columnIndex === 15) {
    if (rowIndex % 2 === 0) {
      return {
        rowspan: 2,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
}

const tabInfo = ref([]);
async function getDataFn() {
  const res: any = await http.corsApi(`/smokeMeeting/contrastSortDetails/${id.value}`, "get", {});
  console.log("getDataFn", res);
  tabInfo.value = res.data;
  if (res.code != 200) return;
  let key = 1;
  // userList.value = []

  let arr2 = [];
  Object.keys(res.data).forEach((userName) => {
    const item: Array<any> = res.data[userName];
    console.log(item);

    arr2.push({ userName: userName, key: key, status: item[0]?.status });
    userList.value = arr2;
    let arr = item.map((ele) => {
      return { ...ele };
    });
    dataMap.set(key, arr);
    key++;
  });
  if (userList.value.length > 0) {
    if (!isStartInter.value || currentUser.value == "") {
      currentUser.value = userList.value[0].key;
      isEditFull.value = userList.value[0].status;
    }

    console.log(userList.value);

    if (!dataMap.has(currentUser.value)) tableData.value = [];

    tableData.value = dataMap.get(currentUser.value);

    blueItem.value = tableData.value;
  }
}

const isEditFull = ref();
/**标签点击 */
function tabClick(e: any, key, status) {
  if (editBtn.value) {
    layer.msg("修改状态不能切换", { icon: 2 });
    return false;
  }
  console.log("点击的对象", e);
  isEditFull.value = status;
  blueItem.value = tabInfo.value[e];
  console.log(blueItem.value);
  currentUser.value = key;

  if (dataMap.has(key)) {
    tableData.value = dataMap.get(key);
  } else {
    tableData.value = [];
  }
}
// function tabClick({ props }: any) {
//   console.log("点击的对象", props);
//   blueItem.value = tabInfo.value[props.label];
//   console.log(blueItem.value);

//   if (dataMap.has(props.name)) {
//     tableData.value = dataMap.get(props.name);
//   } else {
//     tableData.value = [];
//   }
// }

// 修改填写信息
// 修改填写信息
const pad_visible = ref(false);
const showContent = ref([]);
const editBtn = ref(false);
const edit_msg = () => {
  editBtn.value = !editBtn.value;

  if (editBtn.value) {
    clearInterval(timer.value);
  } else {
    startTimer();
  }
};

/**修改行数据 */
async function editSort(line: any) {
  if (tableData.value.length < 1) {
    return;
  }

  http.corsApi("/smokeMeeting/contrastSort", "put", { ...line });
  // if(res.code == 200) {
  //   editBtn.value = false
  //   return ElMessage.success("修改成功")
  // }
}

/** */
function editDescrip(index: number) {
  let row = tableData.value[index + 1];
  console.log(row);
  http.corsApi("/smokeMeeting/contrastSort", "put", { ...row });
}

const padItem = ref([]);
const padKEY = ref("");
const thisRes = ref("");
const edit_pad = (item, key, showArr) => {
  showContent.value = showArr;
  padKEY.value = key;
  console.log(item);
  padItem.value = item;
  pad_visible.value = true;
  thisRes.value = item[key];
};
const edit_pad_enter = async (e) => {
  // padItem.value.
  console.log(padItem.value);
  console.log(padKEY.value);
  console.log(padItem.value[padKEY.value]);
  padItem.value[padKEY.value] = e;
  console.log(e);

  const res = await http.corsApi("/smokeMeeting/contrastSort", "put", { ...padItem.value });
  console.log(res);
  if (res.data) {
    layer.msg("修改成功", { icon: 1, time: 1500 });
    pad_visible.value = false;

    // editBtn.value = false;
  }
};

const blueItem = ref([]);
const blur = async (e) => {
  console.log(e.target.value);
  console.log(blueItem.value[0]);

  let data = blueItem.value[0];
  data.qualitySorting = form.value.qualitySorting;
  data.styleDescription = form.value.styleDescription;

  const res = await http.corsApi("/smokeMeeting/contrastSort", "put", { ...data });
  console.log(res);
  if (res.data) {
    layer.msg("修改成功", { icon: 1, time: 1500 });
    pad_visible.value = false;

    // editBtn.value = false;
  }
};

// input失去焦点时间
const inp_blue = async (item, e) => {
  console.log(item, e);

  const res = await http.corsApi("/smokeMeeting/contrastSort", "put", { ...item });
  console.log(res);
  if (res.data) {
    layer.msg("修改成功", { icon: 1, time: 1500 });
  }
};

const inp_blueNum = async (row, e) => {
  console.log(row, e);

  const res = await http.corsApi("meetingContrastSort/editMeetingContrastSort", "put", {
    allId: row.allId,
    smokeId: row.smokeId,
    firstName: row.firstName,
    endName: row.endName,
    id: row.parentId,
  });
  console.log(res);
  if (res.data) {
    layer.msg("修改成功", { icon: 1, time: 1500 });
  }
  await getDataFn();
};

function backPre() {
  router.go(-1);
}
</script>

<style scoped lang="scss">
.page-view {
  width: 100%;
  height: calc(100% - 42px);
  background-color: #fff;
  .page-top {
    width: 100%;
    padding: 30px;
    background-color: #f5f7fa;
    // display: flex;
    align-items: center;
    // justify-content: center;
    // position: relative;
    .btn {
      // position: absolute;
      right: 30px;
      transform: translateX(-100%);
    }
  }
}
:deep(.el-tabs__content) {
  display: none;
}
:deep(.el-tabs) {
  --el-tabs-header-height: 35px;
}
.line {
  width: 100%;
  height: 40px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  .line-left {
    width: 150px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #ebeef5;
  }
  .line-content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #1f1f1f;
    .def_content {
      color: #999;
    }
  }
}

.smoke_box {
  width: 100%;
  height: max-content;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  .smoke_tip {
    position: absolute;
    right: -10px;
    top: -3px;
    font-size: 12px;
    color: #d31b31;
  }
}
</style>